import Taro from "@tarojs/taro";

const TARO_APP_API = "http://www.zjwtcloud.com:10902/";
export const request = async (
  method: "get" | "post" | "put" | "delete",
  url: string,
  data?: any,
  ifToken: boolean = true,
  headers?: any,
  args?: any
): Promise<{
  responseStatus: string;
  data: any;
  msg: string;
  success: boolean;
} | null> => {
  let headersConfig;
  if (ifToken) {
    const token = Taro.getStorageSync("token");
    console.log("token", token);

    headersConfig = {
      Authorization: token,
      ...headers,
    };
  } else {
    headersConfig = {
      ...headers,
    };
  }
  // @ts-ignore
  let full_url = TARO_APP_API + "api" + url;
  console.log("headersConfig", headersConfig, full_url);

  const res = await Taro.request({
    method,
    url: full_url,
    data,
    header: {
      ...headersConfig,
    },
    ...args,
  });
  let responseClass = null;
  if (res.data.status == "0" || res.data.status == 2000) {
    responseClass = new responseJson(
      "success",
      res.data.data ? res.data.data : res.data,
      res.data.msg
    );
  } else {
    if (res.data.status == 401) {
      Taro.redirectTo({
        url: "/pages/login/index",
      });
      return null;
    }
    responseClass = new responseJson("fail", null, res.data.msg);
  }
  return responseClass;
};

function responseJson(flag, data, msg) {
  this.responseStatus = flag;
  this.data = data;
  this.msg = msg;
  this.success = this.responseStatus === "success";
}
